//
//  PHViewController.m
//  Travel_M_Travel
//
//  Created by Sun on 15/4/6.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "PHViewController.h"
#import "RecommendHandler.h"
#import "UIImageView+WebCache.h"
#import "AboutType_2Data.h"
#import "Type_2addCViewCell.h"
#import "T_2CollectionRView.h"
#import "AboutType_2WayData.h"
#import "UIColor+AddColor.h"

@interface PHViewController ()<UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (nonatomic, retain) UICollectionView *colView;
@property (nonatomic, retain) NSMutableArray *daymesArr;
@property (nonatomic, retain) UIImageView *userPhoto;
@property (nonatomic, retain) UILabel *tripName;
@property (nonatomic, retain) UILabel *timeDay;
@property (nonatomic, retain) T_2CollectionRView *header;
@property (nonatomic, retain) NSMutableArray *photoArray;

@end

@implementation PHViewController

- (void)dealloc{
    [_daymesArr release];
    [_userPhoto release];
    [_tripName release];
    [_timeDay release];
    [_header release];
    [_colView release];
    [_photoData release];
    [super dealloc];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self dataHandler];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
    // 最小行间距
    flowLayout.minimumLineSpacing = 0;
    // 如果有多个区可以拉动
    //    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    // 设定头部 给大小
    [flowLayout setHeaderReferenceSize:CGSizeMake(_colView.frame.size.width, 35)];
    
    
    self.colView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 50, self.view.frame.size.width, self.view.frame.size.height - 160) collectionViewLayout:flowLayout];
    _colView.dataSource = self;
    _colView.delegate = self;
    
    _colView.backgroundColor = [UIColor colorFromHexCode:@"#f6f5ec"];
    
    // 注册cell
    [_colView registerClass:[Type_2addCViewCell class] forCellWithReuseIdentifier:@"zaina"];
    
    // 头部视图注册
    [_colView registerClass:[T_2CollectionRView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"title"];
    
    [self.view addSubview:_colView];
    
    
    [flowLayout release];
    [_colView release];
    
    CGFloat selfWidth = self.view.frame.size.width;
    
    // 作者头像
    self.userPhoto = [[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 40, 40)];
    _userPhoto.clipsToBounds = YES;
    _userPhoto.layer.cornerRadius = 20;
    [self.view addSubview:_userPhoto];
    [_userPhoto release];
    
    //标题
    self.tripName = [[UILabel alloc]initWithFrame:CGRectMake(60, -2, selfWidth - 80, 60 * 3 / 4)];
    _tripName.font = [UIFont fontWithName:@"Helvetica-BoldOblique" size:15];
    //    _titleLable.backgroundColor = [UIColor redColor];
    [self.view addSubview:_tripName];
    [_tripName release];
    
    //时间
    self.timeDay = [[UILabel alloc]initWithFrame:CGRectMake(60, 32, selfWidth - 80, 60/ 4)];
    _timeDay.font = [UIFont fontWithName:@"helvetica" size:12];
    //    _timeDay.backgroundColor = [UIColor blackColor];
    [self.view addSubview:_timeDay];
    [_timeDay release];
    
    
    
    
}

- (void) dataHandler
{
    
    NSString *strIdnumber = [NSString stringWithFormat:@"%@", _photoData.trip_id];
    NSString *str = [[NSString stringWithFormat:@"http://api.breadtrip.com/trips/%@/waypoints/?gallery_mode=1", strIdnumber] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //        NSLog(@"!!!!!!!!!!!!!!%@", str);
    
    
    [RecommendHandler getDataWithUrl:str completion:^(NSDictionary *responseObject) {
        
        
        NSArray *arr = [responseObject objectForKey:@"days"];
        
        NSString *userStr = [[responseObject objectForKey:@"user"] valueForKey:@"avatar_l"];
        
        [self.userPhoto setImageWithURL:[NSURL URLWithString:[userStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
        self.tripName.text = [responseObject objectForKey:@"name"];
        
        NSString *dayStr = [NSString stringWithFormat:@"%@", [responseObject objectForKey:@"day_count"]];
        NSString *firstDay = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"first_day"]];
        self.timeDay.text = [[[ firstDay stringByAppendingString:@"   时长 "]stringByAppendingString:dayStr]stringByAppendingString:@"天"] ;
        
        self.daymesArr = [NSMutableArray array];
        for (NSMutableDictionary *dic in arr) {
            AboutType_2Data *wayData = [[AboutType_2Data alloc] initWithDictionary:dic];
            
            NSMutableArray *dataArr = [dic objectForKey:@"waypoints"];
            NSMutableArray *secArr = [NSMutableArray array];
            
            for (NSMutableDictionary *dic in dataArr) {
                AboutType_2WayData *data = [[AboutType_2WayData alloc] initWithDictionary:dic];
                [secArr addObject:data];
                [self.photoArray addObject:data.photo];
                [data release];
            }
            wayData.waypoints = secArr;
            [self.daymesArr addObject:wayData];
            [wayData release];
            
        }
        [self.colView reloadData];
        
    }];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    if (self.daymesArr.count == 0) {
        return 0;
    }else {
        return self.daymesArr.count;
    }
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.daymesArr.count == 0) {
        return 0;
    }else {
        return [[[self.daymesArr objectAtIndex:section] waypoints] count];
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    Type_2addCViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"zaina" forIndexPath:indexPath];
    AboutType_2Data *type_data = _daymesArr[indexPath.section];
    AboutType_2WayData *data = type_data.waypoints[indexPath.item];
    cell.about2Waydata = data;
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    AboutType_2Data *wayData = _daymesArr[indexPath.section];
    AboutType_2WayData *data = wayData.waypoints[indexPath.item];
    CGFloat imageHeight = [[data.photo_info objectForKey:@"h"] floatValue];
    CGFloat imageWidth = [[data.photo_info objectForKey:@"w"] floatValue];
    NSString *str = data.text;
    
    if (imageWidth == 0) {
        imageWidth = 1;
    }
    
    NSDictionary *dic = @{NSFontAttributeName: [UIFont systemFontOfSize:12]};
    CGRect rect = [str boundingRectWithSize:CGSizeMake(self.colView.frame.size.width, 1000 ) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return CGSizeMake(self.view.frame.size.width - 20 , (self.view.frame.size.width - 20) * imageHeight / imageWidth + rect.size.height + 50);
}


// 添加头部视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableView = nil;
    self.header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"title" forIndexPath:indexPath];
    AboutType_2Data *wayData = [_daymesArr objectAtIndex:indexPath.section];
    _header.type_2Data = wayData;
    reusableView = _header;
    return reusableView;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
